import { message } from 'antd';
import { getToken } from '@/utils/utils';
import { fingerprintFetch } from '@/utils/request';

export const classifyType = {
  vinBI: 1,
  vinWhite: 2,
  vinBlack: 3,
};

export const getCountFn = list => {
  const obj = { vinBI: [], vinWhite: [], vinBlack: [] };
  const arr = Object.entries(classifyType);

  list.forEach(e => {
    arr.find(x => {
      const bool = e.classifyType === x[1];
      if (bool) {
        const { fileUri, fileName } = e;
        const name = fileName || fileUri;
        const pos = name.lastIndexOf('/');
        const str = name.substr(pos + 1);
        // fileUri
        obj[x[0]].push({ ...e, fileName: str, name: str });
      }
      return bool;
    });
  });

  return {
    ...obj,
  };
};

export function comUploadFn(info: any, val: string) {
  const vin = this.state[val];
  
  let { fileList } = info;
  fileList = fileList.slice(-1);

  if (info.file.status === 'done' && info.file.response && info.file.response.responseCode == 200) {
    // let resultList: any[] = [...vin];
    // let count = 0;
    // console.log(fileList,resultList);

    // fileList[0].response.fileRecordList.forEach((item: any) => {
    //   // if (!item.vin) {
    //   //   count += 1;
    //   // } else {
    //   // resultList.push(item.vin);
    //   let bool = true;
    //   if (resultList.length > 0) {
    //     resultList.forEach((e, i) => {
    //       if (e.fileSid === item.sid) {
    //         bool = false;
    //       }
    //       if (i === resultList.length - 1 && bool) {

    //         resultList.push({
    //           // 文件类型 1-BI名单,2-白名单，3-黑名单
    //           classifyType: classifyType[val],
    //           // 文件id
    //           fileSid: item.sid,
    //           // 文件url
    //           fileUri: item.fileUri,
    //           fileName:item.fileName
    //           // 数量
    //           // objectClassifyCount: 0,
    //         });
    //       }
    //     });
    //     return;
    //   }

    //   resultList.push({
    //     // 文件类型 1-BI名单,2-白名单，3-黑名单
    //     classifyType: classifyType[val],
    //     // 文件id
    //     fileSid: item.sid,
    //     // 文件url
    //     fileUri: item.fileUri,
    //     fileName:item.fileName
    //     // 数量
    //     // objectClassifyCount: 0,
    //   });

    //   // }
    // });
    // console.log(resultList);

    // if (count > 0) {
    //   message.error('导入的VIN不存在或车辆未激活！');
    // } else {
    //   message.success(`${info.file.name} 上传成功`);
    //   this.setState({ [val]: resultList });
    // }

    const arr = [...vin];
    const list = fileList[0].response.fileRecordList;
    const newList = [];
    // arr.forEach(e => {
    //   if (e.sid) {
    //     newList.push(e);
    //   }
    // });
    console.log(info.file, list);

    list.forEach(e => {
      newList.push({
        // 文件类型 1-BI名单,2-白名单，3-黑名单
        classifyType: classifyType[val],
        // 文件url
        fileUri: e.fileUri,
        // 文件id
        fileSid: e.sid,
        fileName: info.file.name,
      });
    });
    message.success(`${info.file.name} 上传成功`);
    // console.log(1, newList);
    this.setState({ [val]: newList });
  } else if (
    info.file.status === 'done' &&
    info.file.response &&
    info.file.response.responseCode == 500
  ) {
    message.error(info.file.response.message);
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 上传失败`);
  } else if (info.file.status === 'removed') {
    message.success('文件删除成功');
    this.setState({ [val]: [] });
  }

  // 加载按钮
  const { btnLoading={} } = this.state;
  btnLoading[val] = info.file.status === 'uploading';
  this.setState({
    btnLoading: { ...btnLoading },
  });
}

export function handleExportExcel(recordObj = {}) {
  //   const { formValues, recordObj } = this.state;

  this.setState({ expButtonLoading: true });
  const MAX = 10000;
  // const MAX=getDicByKey(this.context.dicData,'exportMax','enrollActiveReport')?getDicByKey(this.context.dicData,'exportMax','enrollActiveReport'):200;
  const {
    audienceList: {
      pageData: { pagination },
    },
  } = this.props;
  // const str = `${window.g.url}/ordersharing/mapayorder/export`;
  const str = `${window.g.url}/audience/group/export/${recordObj.sid}`;
  const newOptions = {};
  newOptions.method = 'GET';
  newOptions.headers = {
    OptAuthorization: `${getToken()}`,
    // 'Content-Type': 'application/json;charset=utf-8',
  };
  // const newValues = { ...formValues }
  // newOptions.body = JSON.stringify(newValues);

  if (pagination.total <= MAX && pagination.total > 0) {
    fingerprintFetch(str, newOptions)
      .then(response => {
        if (response.status === 200) {
          return response.blob();
        } else {
          this.setState({ expButtonLoading: false });
          throw response;
        }
      })
      .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `受众对象-${new Date().toLocaleDateString()}.xlsx`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
        this.setState({ expButtonLoading: false });
      })
      .catch(err => {
        console.log(err);

        this.setState({ expButtonLoading: false });
        message.error('导出失败，请稍后在试!');
      });
  } else {
    this.setState({ expButtonLoading: false });
    message.warning(`您目前搜索的结果等于0条或者大于${MAX}条，请选择查询条件，精确查询范围！`);
  }
}

export function handFilter(that: any) {
  const { vinBI, vinWhite, vinBlack, recordObj } = that.state;
  const objectGroupName = that.formRef.current.getFieldValue('objectGroupName');
  const obj = {
    ...recordObj,
    list: [...vinBI, ...vinWhite, ...vinBlack],
    objectGroupName,
  };
  that.props.filterClickFn(obj);
}
